package com.hekewangzi.httpProxyClient;

import com.hekewangzi.httpProxyServer.threadPools.ThreadPoolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ProxyServerManager {
    private static final Logger log = LoggerFactory.getLogger(ProxyServerManager.class);
    private ServerSocket serverSocket;
    private volatile boolean running = false;
    private Thread acceptThread;
    private LogCallback logCallback;

    private String now() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    public void start(int listenPort, String serverIp, int serverPort, LogCallback logCallback) {
        if (running)
            return;
        this.logCallback = logCallback;
        running = true;
        acceptThread = new Thread(() -> {
            try {
                serverSocket = new ServerSocket(listenPort);
                if (logCallback != null)
                    logCallback.log(String.format("[%s] [INFO] 代理服务已启动，监听端口: %d，目标服务器: %s:%d", now(), listenPort,
                            serverIp, serverPort));
                while (running) {
                    Socket browserSocket = serverSocket.accept();
                    String clientInfo = browserSocket.getInetAddress().getHostAddress() + ":" + browserSocket.getPort();
                    if (logCallback != null)
                        logCallback.log(String.format("[%s] [INFO] 新客户端连接: %s", now(), clientInfo));
                    ThreadPoolManager.execute(new com.hekewangzi.httpProxyClient.threads.HttpProxyThread(browserSocket,
                            serverIp, serverPort, logCallback));
                }
            } catch (IOException e) {
                if (logCallback != null)
                    logCallback.log(String.format("[%s] [ERROR] 代理服务异常: %s", now(), e.getMessage()));
                log.error("代理服务异常", e);
            } finally {
                stop();
            }
        });
        acceptThread.start();
    }

    public void stop() {
        running = false;
        if (serverSocket != null && !serverSocket.isClosed()) {
            try {
                serverSocket.close();
                // 记录停止日志
                if (logCallback != null)
                    logCallback.log(String.format("[%s] [INFO] 代理服务已停止", now()));
            } catch (IOException e) {
                log.error("关闭ServerSocket异常", e);
            }
        }
        if (acceptThread != null && acceptThread.isAlive()) {
            acceptThread.interrupt();
        }
    }

    public interface LogCallback {
        void log(String msg);
    }
}